<?php

namespace app\admin\controller;

use app\admin\model\Tag;
use app\admin\model\Category;
use think\Controller;
use think\Request;

class Tags extends Controller
{

    public function index()
    {
        $tags = Tag::with('category')->order('id', 'desc')->paginate(8);
//        return $tags;
        return view('Tags/index', compact('tags'));
    }

    /***加载新增页面
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function create()
    {
        $categories = Category::all();
        return view('Tags/create', compact('categories'));
    }

    /***保存新增内容
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function save(Request $request)
    {
        Tag::create($request->param());
        return redirect('Tags/index');
    }

    /***加载编辑页面
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $categories = Category::all();
        $tag = Tag::find($id);
        return view('Tags/edit', compact('tag', 'categories'));
    }

    /***保存编辑内容
     * @param Request $request
     * @param $id
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request, $id)
    {
        $tag = Tag::find($id);
        $tag->allowField(true)->save($request->param(), ['id' => $id]);
        return redirect('Tags/index');
    }

    /***删除
     * @param $id
     * @return \think\response\Redirect
     */
    public function delete($id)
    {
        Tag::destroy($id);
        return redirect('Tags/index');
    }

}